/*=============================================================================
/*=============================================================================
/ MACRO by Jeffrey Sung
/  AddCommentBlock                   (F9)
/  ModifyCommentBlock                (F10)
/  RemoveCommentBlock                (F11)
/  SetComment                        (ALT + B)
/  SetTime                           (ALT + T)
/  AddIFConditionBlock               (F12)
/  SetIFCondition                    (ALT + I)
/  AddSelectionComment               (ALT + C)
/  RemoveSelectionComment            (ALT + R)
/  AddFileHeader                     (CTRL + ALT + H)
/  AddProcedureHeader                (CTRL + ALT + P)
/  CopyFilePath                      (CTRL + =)
/  OpenSelectFile                    (CTRL + ALT + /)
/  RelateFileList                    (CTRL + SHIFT + L)
/  AutoSaveACopy                     (CTRL + SHIFT + B)
/  SetBackupFolder                   (CTRL + ALT + B)
/  AddCompiler0d
/============================================================================*/

/*=============================================================================
/ Update Method
/  1. Copy Utils.em to "My Documents\Source Insight\Projects\Base"
/  2. Open Source Insight
/  3. Open Project - Base
/  4. Project - Synchronize Files
/  5. Load New Configuration from "DEVTLS\EDIT-SET\SourceInsight\GLOBAL.CF3"
/  6. Open Project - Your Project
/  Done.
/============================================================================*/

macro RelateFileList()
{
  hbuf = NewBuf("Results") // create output buffer
  if (hbuf == 0)
  {
    stop
  }
  commentsymbol = GetEnv(COMMSIGN)
	if(commentsymbol == "")
  {
	  commentsymbol = ask("Set Comment Symbol : (EX:IB01410001)")
  }

  SearchForRefs(hbuf, commentsymbol, 0)
  SetCurrentBuf(hbuf) // put buffer in a window

	// ********************************************************
	// Get Path and Filename
	// ********************************************************
  LnCnt = GetBufLineCount(hbuf)
  Ln = 0
  while (Ln < LnCnt)
  {
    sz = GetBufLine(hbuf,Ln)
    szpathend = 0
    szlen = strlen(sz)
    while (szpathend < szlen)
    {
      if (sz[szpathend] == ":")
        break
      szpathend = szpathend + 1
    }
    szpathend = szpathend - 1
    szname = 0
    szlen = strlen(sz)
    while (szname < szlen)
    {
      if (sz[szname] == " ")
        break
      szname = szname + 1
    }
    szpathstart = szname + 2
    if ((szpathend + 2)<szname)
    {
    szfinal = strmid(sz, 0, szpathend + 1)
    } else {
    szfinal = cat (cat (strmid(sz,szpathstart,szpathend), "\\"), strmid(sz, 0, szname))
    }
    PutBufLine(hbuf,Ln,szfinal)
    Ln = Ln + 1
  }

	// ********************************************************
	// Remove repeat file
	// ********************************************************
  LnCnt = GetBufLineCount(hbuf)
  Ln = 0
  while (Ln < LnCnt - 1)
  {
    sz = GetBufLine(hbuf,Ln)
    sznext = GetBufLine(hbuf,Ln+1)
    szptr = 0
    szlen = strlen(sz)
    comp = 0
    while (szptr < szlen)
    {
      if (sz[szptr] != sznext[szptr])
      {
        comp = 1
        break
      }
      szptr = szptr + 1
    }
    if (comp == 0)
    {
      DelBufLine (hbuf, Ln)
      LnCnt = GetBufLineCount(hbuf)
    } else {
      Ln = Ln + 1
    }
  }

	// ********************************************************
	// Reorder filelist
	// ********************************************************
  LnCnt = GetBufLineCount(hbuf)
  Ln = 0
  while (Ln < LnCnt)
  {
    LnComp = Ln + 1
    SmallLn = Ln
    while (LnComp < LnCnt)
    {
      sz = GetBufLine(hbuf,SmallLn)
      sznext = GetBufLine(hbuf,LnComp)

      if(StrCmpOrder(sz, sznext)==1)
      {
        SmallLn = LnComp
      }

      LnComp = LnComp + 1
    }
    sz = GetBufLine(hbuf,SmallLn)
    DelBufLine(hbuf,SmallLn)
    InsBufLine(hbuf, Ln, sz)
    Ln = Ln + 1
  }

	// ********************************************************
	// Add Line Number
	// ********************************************************
  LnCnt = GetBufLineCount(hbuf)
  Ln = 0
  while (Ln < LnCnt)
  {
    sz = GetBufLine(hbuf,Ln)
    sz = cat(". ", sz)
    sz = cat(Ln+1, sz)
    PutBufLine(hbuf,Ln,sz)
    Ln = Ln + 1
  }
}

macro StrCmpOrder(sz, sznext)
{
  szindex = 0
  sznextindex = 0
  
  szflag = strlen(sz) - 1
  while (szflag > 0)
  {
    if (sz[szflag]=="\\")
    {
      break
    }
    szflag = szflag - 1
  }

  sznextflag = strlen(sznext) - 1
  while (sznextflag > 0)
  {
    if (sznext[sznextflag]=="\\")
    {
      break
    }
    sznextflag = sznextflag - 1
  }

  if(szflag!=0&&sznextflag==0)
  {
    return 1
  }
  
  if(szflag==0&&sznextflag!=0)
  {
    return 0
  }

  while (szindex < strlen(sz) && sznextindex < strlen(sznext))
  {
    if(AsciiFromChar(tolower(sz[szindex])) > AsciiFromChar(tolower(sznext[sznextindex])))
    {
      return 1
    }
    if(AsciiFromChar(tolower(sz[szindex])) < AsciiFromChar(tolower(sznext[sznextindex])))
    {
      return 0
    }
    if (sz[szindex+1]!="\\" && sznext[sznextindex+1]!="\\")
    {
      szindex = szindex + 1
      sznextindex = sznextindex + 1
      continue
    }
    while (szindex < strlen(sz))
    {
      if (sz[szindex]=="\\")
      {
        szindex = szindex + 1
        break
      }
      szindex = szindex + 1
    }
    while (sznextindex < strlen(sznext))
    {
      if (sznext[sznextindex]=="\\")
      {
        sznextindex = sznextindex + 1
        break
      }
      sznextindex = sznextindex + 1
    }
  }
  return 0
}

/*=============================================================================
/ AddNVCommentBlock
/============================================================================*/
macro AddNVCommentBlock()
{
	// ********************************************************
	// Get a handle to the current file buffer and the name
	// and location of the current symbol where the cursor is.
	// ********************************************************
	hbuf = GetCurrentBuf()
	hwnd = GetCurrentWnd()
	sel = GetWndSel(hwnd)
	lnF = sel.lnFirst
	lnL = sel.lnLast

	// ********************************************************
	// Make Comment String
	// ********************************************************
	commentstart = ""
	commentend = ""

    commentbody = "(NV-"

	timesymbol = GetEnv(CUSTIME)

	if(timesymbol == ""){
		    commentbody = AddTimeString(commentbody)
        }
	if(timesymbol != ""){
            commentbody = cat(commentbody, timesymbol)
        }

	commentsymbol = GetEnv(COMMSIGN)

	if(commentsymbol == ""){
	        commentsymbol = ask("Set Comment Number : (EX:A, B, C, ...)")
			PutEnv(COMMSIGN,commentsymbol)
        }
	if(commentsymbol != ""){
	        commentbody = cat(commentbody, commentsymbol)
        }

	commentbody = cat(commentbody, "+)");

	// ********************************************************
	// Insert Comment String
	// ********************************************************
	if(sel.lnFirst == sel.lnLast){
		commentbody = AddCommentSymbol(hbuf,commentbody,"")
		sz = GetBufLine(hbuf,lnF)
		sz = cat(sz,cat("	",commentbody))
		PutBufLine(hbuf,lnF,sz)
	   	SetWndSel(hwnd, sel)
	}
	else
	{
		commentbody = AddCommentSymbol(hbuf,commentbody,"")
	   	InsBufLine(hbuf, lnF, commentbody)
	   	InsBufLine(hbuf, lnL+2, commentbody)
	}
   	sel.lnFirst = lnF + 1
   	sel.lnLast = lnL + 1
   	SetWndSel(hwnd, sel)
}

/*=============================================================================
/ RemoveNVCommentBlock
/============================================================================*/
macro RemoveNVCommentBlock()
{
	// ********************************************************
	// Get a handle to the current file buffer and the name
	// and location of the current symbol where the cursor is.
	// ********************************************************
	hbuf = GetCurrentBuf()
	hwnd = GetCurrentWnd()
	sel = GetWndSel(hwnd)
	lnF = sel.lnFirst
	lnL = sel.lnLast

	// ********************************************************
	// Make Comment String
	// ********************************************************
    commentbody = "(NV-"

	timesymbol = GetEnv(CUSTIME)

	if(timesymbol == ""){
		    commentbody = AddTimeString(commentbody)
        }
	if(timesymbol != ""){
            commentbody = cat(commentbody, timesymbol)
        }

	commentsymbol = GetEnv(COMMSIGN)

	if(commentsymbol == ""){
	        commentsymbol = ask("Set Comment Number : (EX:A, B, C, ...)")
			PutEnv(COMMSIGN,commentsymbol)
        }
	if(commentsymbol != ""){
	        commentbody = cat(commentbody, commentsymbol)
        }

	commentbody = cat(commentbody, "-)");

	// ********************************************************
	// Insert Comment String
	// ********************************************************
	if(sel.lnFirst == sel.lnLast){
		commentbody = AddCommentSymbol(hbuf,commentbody,"")
		sz = GetBufLine(hbuf,lnF)
		sz = cat(commentbody,sz)
		PutBufLine(hbuf,lnF,sz)
	   	SetWndSel(hwnd, sel)
	    LnCnt = GetBufLineCount(hbuf)
		if(LnCnt>lnF+1)
	        SetBufIns(hbuf, lnF+1, 0)
		else
	        SetBufIns(hbuf, lnF, 0)
	}
	else
	{
		// ********************************************************
		// Add Comment Block
		// ********************************************************
		ln = lnF
		comment = AddCommentSymbol(hbuf,"","-")
		while(ln <= lnL){
			sz = GetBufLine(hbuf,ln)
			sz = cat(comment,sz)
			PutBufLine(hbuf,ln,sz)
			ln = ln + 1
		}

		// ********************************************************
		// Insert Comment String
		// ********************************************************
		commentbody = AddCommentSymbol(hbuf,commentbody,"")
		InsBufLine(hbuf, lnF, commentbody)
		InsBufLine(hbuf, lnL+2, commentbody)
	}
	sel.lnFirst = lnF + 1
	sel.lnLast = lnL + 1
	SetWndSel(hwnd, sel)
}

/*=============================================================================
/ AddCommentBlock
/============================================================================*/
macro AddCommentBlock()
{
	// ********************************************************
	// Get a handle to the current file buffer and the name
	// and location of the current symbol where the cursor is.
	// ********************************************************
	hbuf = GetCurrentBuf()
	hwnd = GetCurrentWnd()
	sel = GetWndSel(hwnd)
	lnF = sel.lnFirst
	lnL = sel.lnLast

	// ********************************************************
	// Make Comment String
	// ********************************************************
	commentstart = "-start-"
	commentend = "-end-"

    commentbody = ""

	timesymbol = GetEnv(CUSTIME)

	if(timesymbol == ""){
		    commentbody = AddTimeString(commentbody)
        }
	if(timesymbol != ""){
            commentbody = cat(commentbody, timesymbol)
        }

    commentbody = cat(commentbody, "-")

	commentsymbol = GetEnv(COMMSIGN)

	if(commentsymbol == ""){
	        commentsymbol = ask("Set Comment Symbol : (EX:IB01410001)")
			PutEnv(COMMSIGN,commentsymbol)
        }
	if(commentsymbol != ""){
	        commentbody = cat(commentbody, commentsymbol)
        }

    commentstart = cat("[",cat(cat(commentstart,commentbody),"-add]"))
    commentend = cat("[",cat(cat(commentend,commentbody),"-add]"))

	commentstart = AddCommentSymbol(hbuf,commentstart,"")
	commentstart = AddCommentSymbolEnd(hbuf,commentstart)

	commentend = AddCommentSymbol(hbuf,commentend,"")
	commentend = AddCommentSymbolEnd(hbuf,commentend)

	// ********************************************************
	// Insert Comment String
	// ********************************************************
	InsBufLine(hbuf, lnF, commentstart)
	InsBufLine(hbuf, lnL+2, commentend)
	sel.lnFirst = lnF + 1
	sel.lnLast = lnL + 1
	SetWndSel(hwnd, sel)

}

/*=============================================================================
/ ModifyCommentBlock
/============================================================================*/
macro ModifyCommentBlock()
{
	// ********************************************************
	// Get a handle to the current file buffer and the name
	// and location of the current symbol where the cursor is.
	// ********************************************************
	hbuf = GetCurrentBuf()
	hwnd = GetCurrentWnd()
	sel = GetWndSel(hwnd)
	lnF = sel.lnFirst
	lnL = sel.lnLast

	// ********************************************************
	// Make Comment String
	// ********************************************************
	commentstart = "-start-"
	commentend = "-end-"

    commentbody = ""

	timesymbol = GetEnv(CUSTIME)

	if(timesymbol == ""){
		    commentbody = AddTimeString(commentbody)
        }
	if(timesymbol != ""){
            commentbody = cat(commentbody, timesymbol)
        }

    commentbody = cat(commentbody, "-")

	commentsymbol = GetEnv(COMMSIGN)

	if(commentsymbol == ""){
	        commentsymbol = ask("Set Comment Symbol : (EX:IB01410001)")
			PutEnv(COMMSIGN,commentsymbol)
        }
	if(commentsymbol != ""){
	        commentbody = cat(commentbody, commentsymbol)
        }

    commentstart = cat("[",cat(cat(commentstart,commentbody),"-modify]"))
    commentend = cat("[",cat(cat(commentend,commentbody),"-modify]"))

	commentstart = AddCommentSymbol(hbuf,commentstart,"")
	commentstart = AddCommentSymbolEnd(hbuf,commentstart)

	commentend = AddCommentSymbol(hbuf,commentend,"")
	commentend = AddCommentSymbolEnd(hbuf,commentend)

	// ********************************************************
	// Insert Comment String
	// ********************************************************
	InsBufLine(hbuf, lnF, commentstart)
	InsBufLine(hbuf, lnL+2, commentend)
	sel.lnFirst = lnF + 1
	sel.lnLast = lnL + 1
	SetWndSel(hwnd, sel)

}

/*=============================================================================
/ RemoveCommentBlock
/============================================================================*/
macro RemoveCommentBlock()
{
	// ********************************************************
	// Get a handle to the current file buffer and the name
	// and location of the current symbol where the cursor is.
	// ********************************************************
	hbuf = GetCurrentBuf()
	hwnd = GetCurrentWnd()
	sel = GetWndSel(hwnd)
	lnF = sel.lnFirst
	lnL = sel.lnLast

	// ********************************************************
	// Make Comment String
	// ********************************************************
	commentstart = "-start-"
	commentend = "-end-"

    commentbody = ""

	timesymbol = GetEnv(CUSTIME)

	if(timesymbol == ""){
		    commentbody = AddTimeString(commentbody)
        }
	if(timesymbol != ""){
            commentbody = cat(commentbody, timesymbol)
        }

    commentbody = cat(commentbody, "-")

	commentsymbol = GetEnv(COMMSIGN)

	if(commentsymbol == ""){
	        commentsymbol = ask("Set Comment Symbol : (EX:IB01410001)")
			PutEnv(COMMSIGN,commentsymbol)
        }
	if(commentsymbol != ""){
	        commentbody = cat(commentbody, commentsymbol)
        }

    commentstart = cat("[",cat(cat(commentstart,commentbody),"-remove]"))
    commentend = cat("[",cat(cat(commentend,commentbody),"-remove]"))

	commentstart = AddCommentSymbol(hbuf,commentstart,"")
	commentstart = AddCommentSymbolEnd(hbuf,commentstart)

	commentend = AddCommentSymbol(hbuf,commentend,"")
	commentend = AddCommentSymbolEnd(hbuf,commentend)

	// ********************************************************
	// Add Comment Block
	// ********************************************************
	ln = lnF
	comment = AddCommentSymbol(hbuf,"","")
	while(ln <= lnL){
		sz = GetBufLine(hbuf,ln)
		sz = cat(comment,sz)
		PutBufLine(hbuf,ln,sz)
		ln = ln + 1
	}

	// ********************************************************
	// Insert Comment String
	// ********************************************************
	InsBufLine(hbuf, lnF, commentstart)
	InsBufLine(hbuf, lnL+2, commentend)
	sel.lnFirst = lnF + 1
	sel.lnLast = lnL + 1
	SetWndSel(hwnd, sel)

}

/*=============================================================================
/ AddIFConditionBlock
/============================================================================*/
macro AddIFConditionBlock()
{
	// ********************************************************
	// Get a handle to the current file buffer and the name
	// and location of the current symbol where the cursor is.
	// ********************************************************
	hbuf = GetCurrentBuf()
	hwnd = GetCurrentWnd()
	sel = GetWndSel(hwnd)
	lnF = sel.lnFirst
	lnL = sel.lnLast

	ifcondition = GetEnv(IFFLAG)

	if(ifcondition == ""){
	        ifcondition = ask("Set IF Condition :")
        }

	// ********************************************************
	// Get Current file type to make IF Condition String
	// ********************************************************
	name = GetBufProps(hbuf)

    	if (name.Language == "x86 Asm Language" || name.Language == "x86 Assembly")
    	{
    		strifdef = "ifdef "
    		strendifdef = "endif "
    		strif = "if "
    		strendif = "endif "
    	}
    	else
    	{
    		strifdef = "#ifdef "
    		strendif = "#endifdef "
    		strif = "#if "
    		strendif = "#endif "
    	}

        strifdef  = cat(strifdef, "@ifcondition@")
        strendifdef = cat(strendif, AddCommentSymbol(hbuf,strifdef,""))
        strif  = cat(strif, "@ifcondition@")
        strendif = cat(strendif, AddCommentSymbol(hbuf,strif,""))

	// ********************************************************
	// Insert Comment String and If Condition
	// ********************************************************
	InsBufLine(hbuf, lnF, strifdef)
	InsBufLine(hbuf, lnF+1, strif)
	InsBufLine(hbuf, lnL+3, strendif)
	InsBufLine(hbuf, lnL+4, strendifdef)
	sel.lnFirst = lnF + 2
	sel.lnLast = lnL + 2
	SetWndSel(hwnd, sel)
}

/*=============================================================================
/ AddSelectionComment
/============================================================================*/
Macro	AddSelectionComment()
{

	hbuf = GetCurrentBuf()
	hwnd = GetCurrentWnd()
	sel = GetWndSel(hwnd)
	lnF = sel.lnFirst
	lnL = sel.lnLast

	ln = lnF
	comment = AddCommentSymbol(hbuf,"","")
	while(ln <= lnL){
		sz = GetBufLine(hbuf,ln)
		sz = cat(comment,sz)
		PutBufLine(hbuf,ln,sz)
		ln = ln + 1
	}
    LnCnt = GetBufLineCount(hbuf)
	if(LnCnt>lnL+1)
	        SetBufIns(hbuf, lnL+1, 0)
	else
	        SetBufIns(hbuf, lnL, 0)
}

/*=============================================================================
/ RemoveSelectionComment
/============================================================================*/
Macro	RemoveSelectionComment()
{

	hbuf = GetCurrentBuf()
	hwnd = GetCurrentWnd()
	sel = GetWndSel(hwnd)
	lnF = sel.lnFirst
	lnL = sel.lnLast
	ln = lnF

	comment = AddCommentSymbol(hbuf,"","-")
        clen = strlen( comment )
        while(ln <= lnL){
                sz = GetBufLine(hbuf,ln)
                i = 0
                len = strlen( sz )
                while(i<clen && i<=len)
                {
	                IF(sz[0]==comment[i])
	                {
                        sz = strmid(sz, 1, len)
                        len = len - 1
		                PutBufLine(hbuf,ln,sz)
	                }
	                else
	                {
                        break
	                }
	                i = i + 1
	        }
		ln = ln + 1
	}
        LnCnt = GetBufLineCount(hbuf)
	if(LnCnt>lnL+1)
	        SetBufIns(hbuf, lnL+1, 0)
	else
	        SetBufIns(hbuf, lnL, 0)
        }
}

/*=============================================================================
/ RemoveFirstSpace
/============================================================================*/
Macro	RemoveFirstSpace()
{

	hbuf = GetCurrentBuf()
	hwnd = GetCurrentWnd()
	sel = GetWndSel(hwnd)
	lnF = sel.lnFirst
	lnL = sel.lnLast
	ln = lnF

	comment = " "
        clen = strlen( comment )
        while(ln <= lnL){
                sz = GetBufLine(hbuf,ln)
                i = 0
                len = strlen( sz )
                while(i<clen && i<=len)
                {
	                IF(sz[0]==comment[i])
	                {
                                sz = strmid(sz, 1, len)
                                len = len - 1
		                PutBufLine(hbuf,ln,sz)
	                }
	                else
	                {
	                        break
	                }
	                i = i + 1
	        }
		ln = ln + 1
	}
	SetWndSel (hwnd, sel)
}

/*=============================================================================
/ SetTime
/============================================================================*/
Macro	SetTime()
{
	PutEnv(CUSTIME,"")
    timesymbol = ask("Set Customized Date (EX:060804) (Press ESC to Clear Previous Setting):")
	PutEnv(CUSTIME,timesymbol)
}

/*=============================================================================
/ SetComment
/============================================================================*/
Macro	SetComment()
{
	PutEnv(COMMSIGN,"")
    commentsymbol = ask("Set Comment Symbol (EX:IB01410001) (Press ESC to Clear Previous Setting):")
	PutEnv(COMMSIGN,commentsymbol)
}

/*=============================================================================
/ SetIFCondition
/============================================================================*/
Macro	SetIFCondition()
{
	PutEnv(IFFLAG,"")
        ifcondition = ask("Set IF Condition (EX:0, 1, ROMLOAD) (Press ESC to Clear Previous Setting):")
	PutEnv(IFFLAG,ifcondition)
}

/*=============================================================================
/ AddFileHeader
/============================================================================*/
Macro	AddFileHeader()
{
	hbuf = GetCurrentBuf()

	strfile = GetBufName (hbuf)
	fc = 0
	sfc = 0
        while(fc<=strlen(strfile))
        {
                if(strfile[fc]=="\\")
                        sfc = fc
                fc = fc + 1
        }
        strfile = strmid(strfile, sfc+1, strlen(strfile))
//	InsBufLine(hbuf, 0, cat("        TITLE   ",strfile))
        InsBufLine(hbuf, 0, AddCommentSymbol(hbuf,";******************************************************************************",""))
        InsBufLine(hbuf, 1, AddCommentSymbol(hbuf,";* Copyright (c) 1983-2009, Insyde Software Corporation. All Rights Reserved.",""))
        InsBufLine(hbuf, 2, AddCommentSymbol(hbuf,";*",""))
        InsBufLine(hbuf, 3, AddCommentSymbol(hbuf,";* You may not reproduce, distribute, publish, display, perform, modify, adapt,",""))
        InsBufLine(hbuf, 4, AddCommentSymbol(hbuf,";* transmit, broadcast, present, recite, release, license or otherwise exploit",""))
        InsBufLine(hbuf, 5, AddCommentSymbol(hbuf,";* any part of this publication in any form, by any means, without the prior",""))
        InsBufLine(hbuf, 6, AddCommentSymbol(hbuf,";* written permission of Insyde Software Corporation.",""))
        InsBufLine(hbuf, 7, AddCommentSymbol(hbuf,";*",""))
        InsBufLine(hbuf, 8, AddCommentSymbol(hbuf,";******************************************************************************",""))
        InsBufLine(hbuf, 9, AddCommentSymbol(hbuf,"; ModuleName:",""))
        InsBufLine(hbuf, 10, AddCommentSymbol(hbuf,";",""))
        InsBufLine(hbuf, 11, AddCommentSymbol(hbuf,";   ",""))
        InsBufLine(hbuf, 12, AddCommentSymbol(hbuf,";",""))
        InsBufLine(hbuf, 13, AddCommentSymbol(hbuf,";------------------------------------------------------------------------------",""))
        InsBufLine(hbuf, 14, AddCommentSymbol(hbuf,";",""))
        InsBufLine(hbuf, 15, AddCommentSymbol(hbuf,"; Abstract:",""))
        InsBufLine(hbuf, 16, AddCommentSymbol(hbuf,";",""))
        InsBufLine(hbuf, 17, AddCommentSymbol(hbuf,";   ",""))
}

/*=============================================================================
/ AddCompiler0d
/============================================================================*/
Macro	AddCompiler0d()
{
  hbuf = GetCurrentBuf()
  hwnd = GetCurrentWnd()
  sel = GetWndSel(hwnd)
  ln = sel.lnFirst
  InsBufLine(hbuf, ln+0 , "C_PROJ_FLAGS = $(C_PROJ_FLAGS) /Od")
}


/*=============================================================================
/ AddProcedureHeader
/============================================================================*/
Macro	AddProcedureHeader()
{
	hbuf = GetCurrentBuf()
	hwnd = GetCurrentWnd()
	sel = GetWndSel(hwnd)
	ln = sel.lnFirst
	name = GetBufProps(hbuf)
	
	if (name.Language == "x86 Asm Language" || name.Language == "x86 Assembly" || name.Language == "x86")
    {
    	strpro = GetBufSelText (hbuf)
      strlin = "****************************************************************************"
      cnt = 0
      while(cnt<(strlen(strlin)-strlen(strpro)-4))
              strpro = cat(strpro, " ")
      strpro = cat("* ", cat(strpro, " *"))
    
      InsBufLine(hbuf, ln+0 , AddCommentSymbol(hbuf,"****************************************************************************",""))
      InsBufLine(hbuf, ln+1 , AddCommentSymbol(hbuf,strpro,""))
      InsBufLine(hbuf, ln+2 , AddCommentSymbol(hbuf,"*                                                                          *",""))
      InsBufLine(hbuf, ln+3 , AddCommentSymbol(hbuf,"* PURPOSE:                                                                 *",""))
      InsBufLine(hbuf, ln+4 , AddCommentSymbol(hbuf,"* PASSED:                                                                  *",""))
      InsBufLine(hbuf, ln+5 , AddCommentSymbol(hbuf,"* RETURNS:                                                                 *",""))
      InsBufLine(hbuf, ln+6 , AddCommentSymbol(hbuf,"* USES:                                                                    *",""))
      InsBufLine(hbuf, ln+7 , AddCommentSymbol(hbuf,"****************************************************************************",""))
    } else {
      LnIndex = ln
      szflag = 0
      LnCnt = GetBufLineCount(hbuf)
      while (LnIndex<GetBufLineCount(hbuf))
      {
        sz = GetBufLine (hbuf, LnIndex)
        szptr = 0
        while (szptr<strlen(sz))
        {
          if (sz[szptr] == ")")
          {
            szflag = 1
            break
          }
          szptr = szptr + 1
        }
        LnIndex = LnIndex + 1
        if (szflag == 1)
        {
          break
        }
      }
      if (LnIndex == GetBufLineCount(hbuf))
      {
        stop
      }

      InsBufLine(hbuf, LnIndex+0 , "/*++")
      InsBufLine(hbuf, LnIndex+1 , "Routine Description:")
      InsBufLine(hbuf, LnIndex+2 , "  ")
      InsBufLine(hbuf, LnIndex+3 , "Arguments:")
      InsBufLine(hbuf, LnIndex+4 , "  None")
      InsBufLine(hbuf, LnIndex+5 , "Returns:")
      InsBufLine(hbuf, LnIndex+6 , "  None")
      InsBufLine(hbuf, LnIndex+7 , "--*/")
      SetBufIns(hbuf, LnIndex+2, 2)
    }
}

/*=============================================================================
/ Copy File Path
/============================================================================*/
Macro	CopyFilePath()
{
	hbuf = GetCurrentBuf()
	strfile = GetBufName (hbuf)
	ln = 0

  hbuf = NewBuf(Test)
  InsBufLine(hbuf, ln , strfile)
  CopyBufLine (hbuf, ln)
  CloseBuf (hbuf)
}

/*=============================================================================
/ Open Select File
/============================================================================*/
Macro	OpenSelectFile()
{
	hbuf = GetCurrentBuf()
	sel = GetBufSelText (hbuf)
        OpenMiscFile (sel)
}

/*=============================================================================
/ Sub Function
/============================================================================*/

/*=============================================================================
/ AddTimeString
/============================================================================*/
Macro	AddTimeString(sz)
{

	systime = GetSysTime(1)


	
	sz = cat(sz, strmid(systime.year,2,4))
// 	sz = cat(sz, "/")

	if(strlen(systime.month)==1)
	        sz = cat(sz, "0")
	sz = cat(sz, systime.month)
// 	sz = cat(sz, "/")

	if(strlen(systime.day)==1)
	        sz = cat(sz, "0")
	sz = cat(sz, systime.day)

	return	sz
}

/*=============================================================================
/ AddCommentSymbol
/============================================================================*/
Macro	AddCommentSymbol(hbuf,sz,str)
{

	// ********************************************************
	// Get Current file type to determine which comment is ?
	// Asm -> ;
	// Makefile -> #
	// CMD Batch -> rem
	// Other -> //
	// ********************************************************
	name = GetBufProps(hbuf)

	if (name.Language == "x86 Asm Language" || name.Language == "x86 Assembly" || name.Language == "x86")
		sz = cat(cat(";",str),sz)
	else if (name.Language == "CMD Batch" || name.Language == "Batch File")
		sz = cat(cat("REM ",str),sz)
	else if (name.Language == "Makefile")
		sz = cat(cat("#",str),sz)
	else
		sz = cat(cat("//",str),sz)

	return	sz
}

/*=============================================================================
/ AddCommentSymbolEnd
/============================================================================*/
Macro	AddCommentSymbolEnd(hbuf,sz)
{

	// ********************************************************
	// Get Current file type to determine which comment is ?
	// Asm -> ;
	// Makefile -> #
	// CMD Batch -> rem
	// Other -> //
	// ********************************************************
	name = GetBufProps(hbuf)

    	if (name.Language == "x86 Asm Language" || name.Language == "x86 Assembly" || name.Language == "x86")
    		sz = cat(sz,";")
    	else if (name.Language == "CMD Batch")
    		sz = cat(sz,"REM")
    	else if (name.Language == "Makefile")
    		sz = cat(sz,"#")
    	else
    		sz = cat(sz,"//")

	return	sz
}

/*=============================================================================
/ AddAuthor
/============================================================================*/
Macro	AddAuthor(sz)
{

	// ****************************************************************
	// Get the owner's name from the environment variable: MYNAME.
	// If the variable doesn't exist, then the owner field is skipped.
	// ****************************************************************
	MyName = getenv(USERNAME)
	sz = cat(sz, cat(cat(" by ", MyName), " "))

	return	sz
}

/*=============================================================================
/ Auto Save a Copy
/============================================================================*/
macro AutoSaveACopy()
{
	// ********************************************************
	// Get a handle to the current file buffer and the name
	// and location of the current symbol where the cursor is.
	// ********************************************************
	hbuf = GetCurrentBuf()
	strfile = GetBufName (hbuf)
	hbuflen = GetBufLineCount (hbuf)
	hprj = GetCurrentProj ()
    ProjDir = GetProjDir (hprj)
    bakfdrbody = strmid (strfile, strlen(ProjDir), strlen(strfile))
    
	bakfdrsymbol = GetEnv(BAKFDR)

	if(bakfdrsymbol == ""){
	    bakfdrsymbol = ask("Set Backup Folder : (EX:D:\\BIOS\\XXX)")
		PutEnv(BAKFDR,bakfdrsymbol)
    }

	bakfdrbody = cat(bakfdrsymbol, bakfdrbody)

	tbuf = OpenBuf (bakfdrbody)

	if(tbuf == hNil){
		tbuf = NewBuf (bakfdrbody)
	} else {
	    ClearBuf (tbuf)
	}

	SaveBuf (hbuf)

	i=0
	while (i<hbuflen){
		InsBufLine (tbuf, i, GetBufLine (hbuf, i))
		i=i+1
	}
	SaveBuf (tbuf)
	CloseBuf (tbuf)
}

/*=============================================================================
/ Set Backup Folder
/============================================================================*/
Macro	SetBackupFolder()
{
	PutEnv(BAKFDR,"")
    bakfdrsymbol = ask("Set Backup Folder : (EX:D:\\BIOS\\XXX)")
	PutEnv(BAKFDR,bakfdrsymbol)
}


/*=============================================================================
/ CutWindow
/                                                       by Pat.Guo
/============================================================================*/
//=============================================================================
// MACRO : 
// 	PROPOSE	:
//	INPUT	:
// 	OUTPUT	:
//=============================================================================
Macro	CutWindow()
{
	// ********************************************************
	// --------------------------------------------------------
	// Get a handle to the current file buffer and the name
	// and location of the current symbol where the cursor is.
	// --------------------------------------------------------
	// ********************************************************

	hbuf = GetCurrentBuf()
	hwnd = GetCurrentWnd()
        xscroll = GetWndVertScroll (hwnd)

	if (IsWndMax(hwnd))
	{
		Tile_One_Window()
	}
	// --------------------------------------------------------
	// Get Window Rect
	// --------------------------------------------------------
	RectRecord = GetWndRect(hwnd)

	// --------------------------------------------------------
	// Calc Window Size with Frame
	// --------------------------------------------------------
	cxp0 = RectRecord.right - RectRecord.left
	cyp0 = RectRecord.bottom - RectRecord.top

	// --------------------------------------------------------
	// Set First Window postion
	// --------------------------------------------------------
	left0 = RectRecord.left
	right0 = RectRecord.right
	top0 = RectRecord.top
	bottom0 = RectRecord.bottom

	// --------------------------------------------------------
	// Set Offset Pixel Constant
	// --------------------------------------------------------
	ShiftNumber = GetEnv(ShiftPixel)
	if(ShiftNumber == "")
	{
		top = GetWndHighest(top0)
		PutEnv(ShiftPixel,top)
		ShiftNumber = top	
	}
	
	// --------------------------------------------------------
	// Calc Real Postion
	// --------------------------------------------------------
	top0 = top0 - ShiftNumber
	bottom0 = bottom0 - ShiftNumber

	// --------------------------------------------------------
	// Initial Second Cut Window Dim
	// --------------------------------------------------------
	left1 = left0
	top1 = top0
	right1 = right0
	bottom1 = bottom0

	//BufProps = GetBufProps(hbuf)
	//hbuf1 = NewBuf(BufProps.Name)
	//filename = BufProps.Name

	hwnd1 = NewWnd(hbuf)
	key = GetKey()
	if(key == KeyFromChar(Up,0,0,0))
	{
		bottom1 = bottom1 - (cyp0 / 2)
		top0 = top0 + (cyp0 / 2)
	}
	else if (key == KeyFromChar(Down,0,0,0))
	{
		bottom0 = bottom0 - (cyp0 / 2)
		top1 = top1 + (cyp0 / 2)
	}
	else if (key == KeyFromChar(right,0,0,0))
	{
		left1 = left1 + (cxp0 / 2)
		right0 = right0 - (cxp0 / 2)
	}
	else if (key == KeyFromChar(left,0,0,0))
	{
		left0 = left0 + (cxp0 / 2)
		right1 = right1 - (cxp0 / 2)
	}
	
	SetWndRect(hwnd, left0, top0, right0, bottom0)
	SetWndRect(hwnd1, left1, top1, right1, bottom1)
        ScrollWndVert (hwnd1, xscroll)
}

//=============================================================================
// MACRO : 
// 	PROPOSE	:
//	INPUT	:
// 	OUTPUT	:
//=============================================================================
Macro	GetWndHighest(top0)
{
	cwnd = WndListCount()
	iwnd = 0

	while (iwnd < cwnd)
    	{
		hwnd = WndListItem(iwnd)
		
		// --------------------------------------------------------
		// Get Window Rect
		// --------------------------------------------------------
		RectRecord = GetWndRect(hwnd)
		if (RectRecord.top < top0)
		{
			top0 = RectRecord.top
		}
		iwnd = iwnd + 1
	}
	return	top0
}/*=============================================================================
/============================================================================*/
//=============================================================================
// MACRO : 
// 	PROPOSE	:
//	INPUT	:
// 	OUTPUT	:
//=============================================================================
Macro	MargeWindow()
{
	// --------------------------------------------------------
	// Get a handle to the current file buffer and the name
	// and location of the current symbol where the cursor is.
	//	hbuf = current file buffer handle
	// 	hwnd = current window handle
	// 	cwnd = number of window list count
	// 	iwnd = index number of window list
	// 	cbuf = number of file buffer list count
	// --------------------------------------------------------

	hbuf = GetCurrentBuf()
	hwnd = GetCurrentWnd()
	// cwnd = WndListCount()
	// iwnd = 0
	matchnumber = 0
	// cbuf = BufListCount()

	// --------------------------------------------------------
	// Get Window Rect and position
	// --------------------------------------------------------
	RectRecord = GetWndRect(hwnd)
	xscroll = GetWndVertScroll(hwnd)	

	// --------------------------------------------------------
	// Calc Window Size with Frame
	// --------------------------------------------------------
	cxp0 = RectRecord.right - RectRecord.left
	cyp0 = RectRecord.bottom - RectRecord.top

	// --------------------------------------------------------
	// Set First Window postion
	// --------------------------------------------------------
	left0 = RectRecord.left
	right0 = RectRecord.right
	top0 = RectRecord.top
	bottom0 = RectRecord.bottom

	left1 = left0
	right1 = right0
	top1 = top0
	bottom1 = bottom0

	// --------------------------------------------------------
	// Set Offset Pixel Constant
	// --------------------------------------------------------
	ShiftNumber = GetEnv(ShiftPixel)
	if(ShiftNumber == "")
	{
		top = GetWndHighest(top0)
		PutEnv(ShiftPixel,top)
		ShiftNumber = top	
	}

	// --------------------------------------------------------
	// Get Marge Window direct
	// --------------------------------------------------------
	key = GetKey()
	if(key == KeyFromChar(Up,0,0,0))		// Up
	{
		top1 = top0 - cyp0
		bottom1 = top0
		top0 = top0 - cyp0

	}
	else if (key == KeyFromChar(Down,0,0,0))	// Down
	{
		top1 = bottom0
		bottom1 = bottom0 + cyp0
		bottom0 = bottom0 + cyp0
	}
	else if (key == KeyFromChar(right,0,0,0))	// Right
	{
		left1 = right0
		right1 = right0 + cxp0
		right0 = right0 + cxp0
	}
	else if (key == KeyFromChar(left,0,0,0))	// Left
	{
		left1 = left0 - cxp0
		right1 = left0
		left0 = left0 - cxp0
	}
	else
	{
		Msg("[ Error Key !]")
		stop()
	}

	matchnumber = GetMatchWnd(hbuf, top1, bottom1, left1, right1)
	if (matchnumber)
	{
		MargeAllWnd(top0, bottom0, left0, right0)	
	}
	SetCurrentWnd (hwnd)
}
//=============================================================================
// MACRO : 
// 	PROPOSE	:
//	INPUT	:
// 	OUTPUT	:
//=============================================================================
Macro	MargeAllWnd(top0, bottom0, left0, right0)
{
	cwnd = WndListCount()
	iwnd = 0
	ShiftNumber = GetEnv(ShiftPixel)
	

	while (iwnd < cwnd)
    {
		hwnd = WndListItem(iwnd)
		matchside = GetMatchWndSide(hwnd, top0, bottom0, left0, right0)
		SameFBufWndNum = 0

		// --------------------------------------------------------
		// Check Window Match Marge Size
		// --------------------------------------------------------
		if (matchside >= 3)
		{
			jwnd = 0
			while (jwnd < iwnd)
			{
				hwnd1 = WndListItem(jwnd)
				if (GetWndBuf(hwnd) == GetWndBuf(hwnd1) && (GetMatchWndSide(hwnd1, top0, bottom0, left0, right0) >= 3))
				{
					SameFBufWndNum = SameFBufWndNum + 1
				}
				jwnd = jwnd + 1
			}
			
			if (SameFBufWndNum)
			{
				CloseWnd(hwnd)
				cwnd = cwnd - 1
			}
			else
			{
				SetWndRect(hwnd, left0, top0 - ShiftNumber, right0, bottom0 - ShiftNumber)
			}
		}

		iwnd = iwnd + 1
	}

}
//=============================================================================
// MACRO : 
// 	PROPOSE	:
//	INPUT	:
// 	OUTPUT	:
//=============================================================================
Macro GetMatchWndSide(hwnd, top0, bottom0, left0, right0)
{
	matchside = 0

	// --------------------------------------------------------
	// Get Window Rect
	// --------------------------------------------------------
	RectRecord = GetWndRect(hwnd)

	// --------------------------------------------------------
	// Check Marge Side Number
	// --------------------------------------------------------
	if (RectRecord.top == top0)
	{
		matchside = matchside + 1
	}
	if (RectRecord.left == left0)
	{
		matchside = matchside + 1
	}
	if (RectRecord.right == right0)
	{
		matchside = matchside + 1
	}
	if (RectRecord.bottom == bottom0)
	{
		matchside = matchside + 1
	}
	Return	matchside
}

//=============================================================================
// MACRO : 
// 	PROPOSE	:
//	INPUT	:
// 	OUTPUT	:
//=============================================================================
Macro	GetMatchWnd(hbuf, top1, bottom1, left1, right1)
{
	cwnd = WndListCount()
	iwnd = 0
	matchnumber = 0
	while (iwnd < cwnd)
    	{
		hwnd = WndListItem(iwnd)
		
		// --------------------------------------------------------
		// Get Window Rect
		// --------------------------------------------------------
		RectRecord = GetWndRect(hwnd)
		if ((RectRecord.top == top1) && (RectRecord.bottom == bottom1) && (RectRecord.left == left1) && (RectRecord.right == right1))
		{
			if (GetWndBuf(hwnd) == hbuf)
			{
				CloseWnd(hwnd)
				cwnd = cwnd - 1
				iwnd = iwnd - 1
 			}
			//else
			//{
				matchnumber = matchnumber + 1
			//}	
		}
		iwnd = iwnd + 1
	}
	Return	matchnumber
}



// Finds matching scoping delimiters and jumps to them.
// If the cursor is not positioned on a delimiter but is inside 
// a matching part the macro will jump to the start of the closest
// scope. Currently matches [],(),<>,{}
macro siMatchDelim2()
{
	hwnd = GetCurrentWnd()
	buff = GetCurrentBuf()
    if (hwnd != 0 && buff != 0 )
	{
		sel = GetWndSel(hwnd)
        cur_line = GetBufLine( buff, sel.lnFirst )
        cur_char = cur_line[sel.ichFirst]
        match_sel = 0

        
		if( siIsLeftDelim( cur_line, sel.ichFirst ) )
            match_sel = siMatchLeftDelim( cur_char, buff, sel, hwnd )
		else if( siIsRightDelim( cur_line, sel.ichFirst ) )
  		    match_sel = siMatchRightDelim( cur_char, buff, sel, hwnd )
		else
            match_sel = siFindFirstLeftDelim(buff, sel, hwnd )

		if( match_sel )
		{
    	    match_sel.lnLast = match_sel.lnFirst
    	    match_sel.ichLim = match_sel.ichFirst
		    SetWndSel( hwnd, match_sel )

		    // If the new selection is not visible scroll to it
			_tsUpdateInsertion(hwnd, match_sel)
		}
	}
}


macro _tsUpdateInsertion(hwnd, sel)
{
	lnTop = GetWndVertScroll(hwnd);
	cLines = GetWndLineCount(hwnd);

	if (lnTop > sel.lnFirst)
	{
		ScrollWndToLine(hwnd, sel.lnFirst); 
	}

	if (lnTop + cLines <= sel.lnFirst)
	{
		lnTop = sel.lnLast - cLines + 1;
		ScrollWndToLine(hwnd, lnTop); 
	}
}



macro siMatchLeftDelim( left_delim, buff, sel, hwnd )
{
    // Special case paren because the built in stuff is much faster
    if( cur_char == "(" )
    {
        Paren_Right
		return GetWndSel(hwnd)
    }
    
    right_delim = siGetRightDelim( left_delim )
    nest = 1
    
    cur_line = sel.lnFirst
    cur_pos = sel.ichFirst + 1
    
    buff_lines = GetBufLineCount(buff) 
    while( cur_line < buff_lines )
    {
        line = GetBufLine( buff, cur_line )
        line_len = GetBufLineLength( buff, cur_line )
        while( cur_pos < line_len )
        {
            if( line[cur_pos] == left_delim )
                nest = nest + 1
            else if( line[cur_pos] == right_delim )
            {
                nest = nest - 1
                if( nest == 0 )
                {
                    sel.lnFirst = cur_line
                    sel.ichFirst = cur_pos
                    return sel
                }
            }

            cur_pos = cur_pos + 1
        }

        cur_line = cur_line + 1
        cur_pos = 0;
    }

    return 0
}

macro siMatchRightDelim( right_delim, buff, sel, hwnd )
{
    // Special case paren because the built in stuff is much faster
    if( cur_char == ")" )
    {
        Paren_Left
		return GetWndSel(hwnd)
    }
            
    left_delim = siGetLeftDelim( right_delim )
    nest = 1
    
    cur_line = sel.lnFirst
    cur_pos = sel.ichFirst - 1
    
    while( cur_line >= 0 )
    {
        line = GetBufLine( buff, cur_line )
        while( cur_pos >= 0 )
        {
            if( line[cur_pos] == right_delim )
                nest = nest + 1
            else if( line[cur_pos] == left_delim )
            {
                nest = nest - 1
                if( nest == 0 )
                {
                    sel.lnFirst = cur_line
                    sel.ichFirst = cur_pos
                    return sel
                }
            }

            cur_pos = cur_pos - 1
        }

        cur_line = cur_line - 1
        if( cur_line >= 0 )
            cur_pos = GetBufLineLength( buff, cur_line )
    }

    return 0
}

macro siFindFirstLeftDelim( buff, sel, hwnd )
{
    while( sel.lnFirst >= 0 )
    {
        line = GetBufLine( buff, sel.lnFirst )
        while( sel.ichFirst >= 0 )
        {
            if( siIsRightDelim( line, sel.ichFirst ) )
            {
                jump_sel = siMatchRightDelim( line[sel.ichFirst], buff, sel, hwnd )
                if( jump_sel )
                {
                    sel = jump_sel
                    line = GetBufLine( buff, sel.lnFirst )
                }
            }
            else if( siIsLeftDelim( line, sel.ichFirst) )
            {
                return sel
            }

            sel.ichFirst = sel.ichFirst - 1
        }

        sel.lnFirst = sel.lnFirst - 1
        if( sel.lnFirst >= 0 )
            sel.ichFirst = GetBufLineLength( buff, sel.lnFirst )
    }

    return 0
}


macro siIsLeftDelim( line, pos )
{
    if( line[pos] == "(" ||
        line[pos] == "{" ||
        line[pos] == "[" ||
        line[pos] == "<"    )
        return 1
    else
        return 0
}

macro siIsRightDelim( line, pos )
{
    back_pos = 0
    if( pos > 0 )
        back_pos = pos - 1

    if( line[pos] == ")" ||
        line[pos] == "}" ||
        line[pos] == "]" ||
        // The account for C-style pointer->member
        (line[pos] == ">" && (pos == 0 || line[back_pos] != "-")   )
        return 1
    else
        return 0
}

macro siGetRightDelim( left_delim )
{
    if( left_delim == "(" )
        return ")"
    else if( left_delim == "{" )
        return  "}"
    else if( left_delim == "[" )
        return  "]"
    else if( left_delim == "<" )
        return  ">"
    else
        return "-"
}

macro siGetLeftDelim( right_delim )
{
    if( right_delim == ")" )
        return "("
    else if( right_delim == "}" )
        return  "{"
    else if( right_delim == "]" )
        return  "["
    else if( right_delim == ">" )
        return  "<"
    else
        return "-"
}


// SI does not include \n in buffer
macro siNormSel(hbuf, sel)
{
	if (sel.ichLim >= GetBufLineLength(hbuf, sel.lnLast))
	{
		sel.lnLast = sel.lnLast + 1
		sel.ichLim = 0
    }

	return sel
}


